<div class="open-form">
    <div class="open-model">
        <div class="open-auto">
            <!-- 头部操作栏 -->
            <div class="layui-form toolbar">
                <div class="layui-form-item">
                    <div class="layui-inline">
                        <label class="layui-form-label w-auto">名称：</label>
                        <div class="layui-input-inline mr0">
                            <input name="name" class="layui-input" type="text" placeholder="请输入名称"/>
                        </div>
                    </div>
                    <div class="layui-inline">
                        <button class="layui-btn icon-btn" lay-filter="attrTableFormSubSearchLog" lay-submit
                                layui-form-keyDownSearch="true"><i class="layui-icon">&#xe615;</i>搜索
                        </button>
                        <button id="productAttrBtnAdd" class="layui-btn icon-btn"><i class="layui-icon">&#xe654;</i>添加
                        </button>
                        <button id="productAttrCategoryBtnAdd" class="layui-btn icon-btn"><i
                                class="layui-icon">&#xe654;</i>添加分类
                        </button>
                        <button id="productAttrBtnDel" class="layui-btn icon-btn layui-btn-danger"><i
                                class="layui-icon"></i>批量删除
                        </button>
                    </div>
                </div>
            </div>
            <!-- 表格 -->
            <table class="layui-table" id="productAttrTable" lay-filter="productAttrTable"></table>
        </div>
        <div class="layui-form-item text-right">
            <button class="layui-btn layui-btn-primary" type="button" ew-event="closeDialog">取消</button>
        </div>
    </div>
</div>


<script type="text/html" id="productAttrTableBar">
    <a class="layui-btn layui-btn-warm layui-btn-xs" lay-event="editAttr">修改</a>
    <a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="del">删除</a>
</script>

<!-- 表单弹窗 -->
<script type="text/html" id="productAttrForm">
    <form lay-filter="productAttrForm" class="layui-form model-form" style="padding-top: 20px;">
        <input name="id" type="hidden"/>
        <div class="layui-form-item">
            <label class="layui-form-label">物料类别</label>
            <div class="layui-input-block">
                <select name="productTypeId" lay-filter="productTypeId" lay-search lay-verify="required" disabled>
                </select>
            </div>
        </div>

        <div class="layui-form-item">
            <label class="layui-form-label">属性分类</label>
            <input name="categoryId" type="hidden"/>
            <div class="layui-input-block" id="selectProductAttrCategory">
            </div>
        </div>

        <div class="layui-form-item">
            <label class="layui-form-label">属性名称</label>
            <div class="layui-input-block">
                <input name="attrName" placeholder="请输入名称" type="text" class="layui-input" lay-verify="required"
                       required/>
            </div>
        </div>

        <div class="layui-form-item">
            <label class="layui-form-label">描述</label>
            <div class="layui-input-block">
                <textarea name="remark" placeholder="请输入描述" class="layui-textarea"/>
            </div>
        </div>

        <div class="layui-form-item">
            <label class="layui-form-label">是否启用</label>
            <div class="layui-input-block">
                <input name="isDeleted" type="checkbox" lay-skin="switch" value="1" checked="false"
                       lay-text="启用|停用"/>
            </div>
        </div>

        <div class="layui-form-item">
            <label class="layui-form-label">排序</label>
            <div class="layui-input-block">
                <input name="sortNumber" placeholder="请输入排序" type="text" class="layui-input" lay-verify=""
                       required/>
            </div>
        </div>

        <div class="layui-form-item">
            <label class="layui-form-label">属性类别</label>
            <div class="layui-input-block">
                <select name="style" lay-filter="style" lay-verify="required" required>
                    <option value="">请选择属性类别</option>
                    <option value="text">文本</option>
                    <option value="single">固定选择项</option>
                </select>
            </div>
        </div>

        <div class="layui-form-item" id="btnAddDiv2">
            <label class="layui-form-label"></label>
            <div class="layui-input-inline">
                <button id="btnAdd2" class="layui-btn" lay-filter="btnAdd2" onclick="return false;">添加选择项</button>
            </div>
        </div>

        <div class="layui-form-item text-right">
            <button class="layui-btn layui-btn-primary" type="button" ew-event="closeDialog">取消</button>
            <button class="layui-btn" lay-filter="productAttrFormSubmit" lay-submit>保存</button>
        </div>
    </form>
</script>


<script type="text/html" id="productAttributeCategoryForm">
    <form lay-filter="productAttributeCategoryForm" class="layui-form model-form">
        <input name="id" type="hidden"/>

        <div class="layui-form-item">
            <label class="layui-form-label">物料类别</label>
            <div class="layui-input-block">
                <select name="productTypeId" lay-filter="productTypeId" lay-search lay-verify="required" disabled>

                </select>
            </div>
        </div>

        <div class="layui-form-item" id="PID">
            <label class="layui-form-label">所属分类</label>
            <input name="parentId" type="hidden"/>
            <div class="layui-input-block" id="selectCategory4AttrCategory">
            </div>
        </div>

        <div class="layui-form-item">
            <label class="layui-form-label">名称</label>
            <div class="layui-input-block">
                <input name="name" placeholder="请输入名称" type="text" class="layui-input" lay-verify="required"
                       required/>
            </div>
        </div>

        <div class="layui-form-item">
            <label class="layui-form-label">描述</label>
            <div class="layui-input-block">
                <textarea id="remark" name="remark" placeholder="请输入描述" class="layui-textarea"/>
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">是否终极分类</label>
            <div class="layui-input-block">
                <select id="isFinal" name="isFinal" lay-filter="isFinal" lay-search
                        lay-verify="required"></select>
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">是否启用</label>
            <div class="layui-input-block">
                <select id="isDeleted" name="isDeleted" lay-filter="isDeleted" lay-search
                        lay-verify="required"></select>
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">排序</label>
            <div class="layui-input-block">
                <input name="sortNumber" placeholder="请输入排序" type="text" class="layui-input" lay-verify=""
                       required/>
            </div>
        </div>
        <div class="layui-form-item text-right">
            <button class="layui-btn layui-btn-primary" type="button" ew-event="closeDialog">取消</button>
            <button class="layui-btn" lay-filter="productAttributeCategoryFormSubmit" lay-submit>保存</button>
        </div>
    </form>
</script>

<!-- js部分 -->
<script>
    layui.use(['layer', 'form', 'table', 'laydate', 'admin', 'laytpl', 'tableTreeDj', 'config'], function () {
        var $ = layui.jquery;
        var layer = layui.layer;
        var form = layui.form;
        var table = layui.table;
        var laydate = layui.laydate;
        var config = layui.config;
        var admin = layui.admin;
        var upload = layui.upload;
        var laytpl = layui.laytpl;
        var tableTree = layui.tableTreeDj;

        // 回显属性数据
        var data = admin.getTempData('data');

        // 渲染表格
        var insTb = table.render({
            elem: '#productAttrTable',
            url: config.base + 'enterprise/product/admin/productAttribute/list?productType=' + data.id,
            page: true,
            cellMinWidth: 100,
            cols: [[
                {type: 'checkbox'}
                , {type: 'numbers', title: '序号'}
                , {field: 'name', align: 'center', title: '属性名称'}
                // , {field: 'attrHeader', align: 'center', title: '属性头'}
                , {field: 'categoryName', align: 'center', title: '属性分类'}
                , {field: 'productTypeName', align: 'center', title: '物料类别'}
                , {
                    field: 'style', align: 'center', title: '属性类别', templet: function (d) {
                        if (d.style == 'text') {
                            return '文本';
                        } else if (d.style == 'single') {
                            return '单选';
                        }
                    }
                }
                , {field: 'attrValues', align: 'center', title: '属性值'}
                , {field: 'sortNumber', align: 'center', title: '排序'}
                , {
                    field: 'isDeleted', align: 'center', title: '是否启用', templet: function (d) {
                        if (d.isDeleted) {
                            return '<input name="isDeleted" type="checkbox" lay-skin="switch" value="' + d.id + '" checked="' + d.isDeleted + '" lay-filter="isDeleted"  lay-text="启用|停用"/>';
                        } else {
                            return '<input name="isDeleted" type="checkbox" lay-skin="switch" value="' + d.id + '" lay-filter="isDeleted"   lay-text="启用|停用"/>';
                        }

                    }
                }
                , {field: 'createTime', align: 'center', title: '创建时间', width: 160}
                , {align: 'center', toolbar: '#productAttrTableBar', title: '操作', width: 200}
            ]],
            done: function (res, curr, count) {
            }
        });

        // 工具条点击事件
        table.on('tool(productAttrTable)', function (obj) {
            var data = obj.data;
            if (obj.event === 'editAttr') { //修改
                data.eventType = 'editAttr'
                showEditAttrModel(data);
            } else if (obj.event === 'del') { // 删除
                doDelete(obj);
            }
        });

        function doDelete(obj) {
            layer.confirm('确定要删除吗？', {
                offset: '65px',
                skin: 'layui-layer-admin'
            }, function (i) {
                layer.close(i);
                layer.load(2);
                admin.req('enterprise/product/admin/productAttribute/' + obj.data.id, {}, function (res) {
                    layer.closeAll('loading');
                    if (res.code == 200) {
                        layer.msg(res.msg, {icon: 1});
                        obj.del();
                        table.reload('productAttrTable');
                    } else {
                        layer.msg(res.msg, {icon: 2});
                    }
                }, 'DELETE');
            });
        }

        //监听排序
        table.on('sort(productAttrTable)', function (obj) {
            table.reload('productAttrTable', {
                initSort: obj
                , where: {
                    sort: obj.field
                    , order: obj.type
                }
            });
        });

        // 搜索
        form.on('submit(attrTableFormSubSearchLog)', function (data) {
            insTb.reload({where: data.field, page: {curr: 1}}, 'data');
        });

        form.on('switch(isDeleted)', function (obj) {
            if (obj.elem.checked) {
                enable(obj.value)
            } else {
                disable(obj.value)
            }
        })

        function enable(id) {
            admin.req('enterprise/product/admin/productAttribute/enable', {id: id}, function (res) {
                if (res.code == 200) {
                    layer.msg(res.msg, {icon: 1});
                    table.reload('productAttrTable');
                } else {
                    layer.msg(res.msg, {icon: 2});
                }
            }, 'GET');
        }

        function disable(id) {
            admin.req('enterprise/product/admin/productAttribute/disable', {id: id}, function (res) {
                if (res.code == 200) {
                    layer.msg(res.msg, {icon: 1});
                    table.reload('productAttrTable');
                } else {
                    layer.msg(res.msg, {icon: 2});
                }
            }, 'GET');
        }

        // 添加按钮点击事件
        $('#productAttrBtnAdd').click(function () {
            data.eventType = 'addAttrFromAttrTable'
            showEditAttrModel(data);
        });

        $('#productAttrCategoryBtnAdd').click(function () {
            data.eventType = 'addAttrFromAttrTable'
            showEditAttrCategoryModel(data, 'productAttributeCategoryForm', 'productAttributeCategoryFormSubmit');
        });

        $('#productAttrBtnDel').click(function () {
            var checkRows = table.checkStatus('productAttrTable');
            if (checkRows.data.length == 0) {
                layer.msg('请选择要删除的数据', {icon: 2});
            } else {
                var ids = '';
                checkRows.data.forEach(item => {
                    ids += item.id + ','
                })
                delBatch(ids)
            }
        });

        function delBatch(ids) {
            admin.req('enterprise/product/admin/productAttribute/delBatch', {ids: ids}, function (res) {
                if (res.code == 200) {
                    layer.msg(res.msg, {icon: 1});
                    table.reload('productAttrTable');
                } else {
                    layer.msg(res.msg, {icon: 2});
                }
            }, 'POST');
        }


        function showEditAttrModel(data) {
            var openIndex = admin.open({
                type: 1,
                area: '640px',
                offset: '120px',
                title: data && (data.eventType == 'addAttr' || data.eventType == 'addAttrFromAttrTable') ? '添加物料属性' : '修改物料属性',
                content: $('#productAttrForm').html(),
                success: function () {
                    console.info(data.productType, 9090);
                    console.info(data.materialNature, 9091);
                    //属性分类
                    admin.initDataSelectTree(true, 'enterprise/product/admin/productAttributeCategory/getTreeData', {productType: data.productType, materialNature: data.materialNature}, 'selectProductAttrCategory', data ? data.categoryId : null, "属性分类", 'categoryId', null);

                    var productTypeName = '';
                    if (data && data.eventType == 'editAttr') {
                        productTypeName = data.productTypeName;
                        data.attrName = data.name;
                    } else {
                        productTypeName = data.name;
                    }
                    var option = '<option selected>' + productTypeName + '</option>'
                    $("form select[name='productTypeId']").html(option);
                    form.render('select')
                    if (data && data.eventType == 'addAttr') {
                        data.sortNumber = '';
                    }
                    form.val('productAttrForm', data);
                    form.render();

                    var getTemplateHtml = function (i) {
                        var labelName = '';
                        var valLen = $("form input[name='value']").length;
                        var classNew = '';
                        if (valLen == 0) {
                            labelName = '属性值';
                        } else {
                            classNew = 'newAdd'
                        }
                        var templateHtml = '' +
                            '<div class="attributeDiv layui-form-item ' + classNew + '" >' +
                            '<div class="layui-form-item">' +
                            '<div >' +
                            '<label class="layui-form-label" >' + labelName + '</label>' +
                            '<div class="layui-input-inline">' +
                            '<input id="value' + i + '" name="value" placeholder="请输入属性" type="text" class="layui-input" lay-verify="required" required/>' +
                            '</div>' +
                            '</div>' +
                            '<div >' +
                            '</div>';
                        templateHtml += '<div class="layui-input-inline">' +
                            '<button id="btnDel' + i + '" class="layui-btn delBtn" lay-filter="btnDel' + i + '" style="margin-left: 20px;">删除</button>' +
                            '</div>';
                        templateHtml += '</div>' + '</div>';
                        return templateHtml;
                    }

                    var i = 0;
                    var addTemplateDiv = function () {
                        var html = getTemplateHtml(i++);
                        $("#btnAddDiv2").prev().after(html);
                        form.render();
                        form.render('select');
                        $(".delBtn").off('click').on('click', function () {
                            var btn = $(this);
                            var btnId = btn[0].id;
                            var btnNo = btnId.substring("btnDel".length, btnId.length);
                            btn.parent().parent().parent().remove();
                        });
                    };

                    $('#btnAdd2').click(addTemplateDiv);
                    if (data && (data.eventType == 'addAttr' || data.eventType == 'addAttrFromAttrTable')) {
                        $("#btnAdd2").hide();
                    }
                    form.on('select(style)', function (data) {
                        if (data.value == 'text') {
                            $("#btnAdd2").hide();
                            $(".attributeDiv").remove();
                        } else if (data.value == 'single') {
                            $("#btnAdd2").show();
                            if ($("form input[name='value']").length == 0) {
                                addTemplateDiv();
                                $("#btnDel0").hide();
                            }
                        }
                    })
                    if (data && data.eventType == 'editAttr') {
                        if (data.style == 'single') {
                            $("#btnAdd2").show();
                        } else {
                            $("#btnAdd2").hide();
                        }
                    }

                    /*if(data==undefined||(data&&(data.eventType=='addAttr'||data.eventType=='addAttrFromAttrTable'))){
                        addTemplateDiv();
                        $("#btnDel0").hide();
                    }*/


                    if (data && data.eventType == 'editAttr') {
                        admin.req('enterprise/product/admin/productAttributeValue/list', {
                            productAttributeId: data.id,
                            limit: 9999
                        }, function (res) {
                            if (res.code == 200) {
                                for (var k = 0; k < res.data.length; k++) {
                                    addTemplateDiv();
                                    $("#btnDel0").hide();
                                    var elementNo = i - 1;
                                    var value = res.data[k].value;
                                    $("#value" + elementNo).val(value);
                                    form.render();
                                }

                            } else {
                                layer.msg('获取属性值失败', {icon: 2, time: 1000});
                            }
                        }, 'GET');
                    }

                    // 表单提交事件
                    form.on('submit(productAttrFormSubmit)', function (d) {
                        layer.load(2);
                        var detailList = [];
                        var vals = [];
                        var sorts = [];
                        $("form input[name='value']").each(function (index, item) {
                            var val = $(this).val();
                            vals.push(val);
                        });
                        if (d.field.style == 'single' && vals.length == 0) {
                            layer.msg('请添加固定值选择项', {icon: 2});
                            layer.closeAll('loading');
                            return false;
                        }


                        for (var k = 0; k < vals.length; k++) {
                            var obj = {value: vals[k]};
                            detailList.push(obj)
                        }
                        if (data && (data.eventType == 'addAttr' || data.eventType == 'addAttrFromAttrTable')) {
                            d.field.id = undefined;
                            d.field.productType = data.id;
                        } else {
                            d.field.productType = data.productType;
                        }
                        d.field.name = d.field.attrName;
                        d.field.detailList = detailList;
                        var isDeleted = $("form input[name='isDeleted']").prop("checked");
                        if (!isDeleted) {
                            d.field.isDeleted = false;
                        } else {
                            d.field.isDeleted = true;
                        }
                        admin.req(data && (data.eventType == 'addAttr' || data.eventType == 'addAttrFromAttrTable') ? 'enterprise/product/admin/productAttribute/add' : 'enterprise/product/admin/productAttribute/update', JSON.stringify(d.field), function (res) {
                            layer.closeAll('loading');
                            if (res.code == 200) {
                                layer.msg(res.msg, {icon: 1});
                                if (data && (data.eventType == 'addAttrFromAttrTable' || data.eventType == 'editAttr')) {
                                    table.reload('productAttrTable');
                                    layer.close(openIndex);
                                } else {
                                    layer.closeAll('page');
                                }

                            } else {
                                layer.msg(res.msg, {icon: 2});
                            }
                        }, 'POST', true, 'application/json; charset=utf-8');
                        return false;
                    });
                }
            });
        }

        function showEditAttrCategoryModel(productTypeData, data, formId, submitButton, parentIdVal) {
            var openCategoryIndex = admin.open({
                type: 1,
                area: '540px',
                offset: '120px',
                title: '添加属性分类',
                content: $('#productAttributeCategoryForm').html(),
                success: function () {
                    var productTypeName = productTypeData.name;
                    var option = '<option selected>' + productTypeName + '</option>'
                    $("form select[name='productTypeId']").html(option);
                    form.render('select')

                    //所属分类
                    admin.initDataSelectTree(true, 'enterprise/product/admin/productAttributeCategory/getTreeData', {productType: productTypeData.id}, 'selectCategory4AttrCategory', data.categoryId, "所属分类", 'parentId', null);
                    //是否终极分类
                    admin.getDictList("isFinal", "sys_yes_no", 1, "是否终极分类");
                    //是否启用
                    admin.getDictList("isDeleted", "sys_yes_no", 0, "是否启用");

                    // 表单提交事件
                    form.on('submit(productAttributeCategoryFormSubmit)', function (d) {
                        layer.load(2);
                        if (d.field.parentId == null || d.field.parentId == '') {
                            d.field.parentId = -1
                        }
                        d.field.productType = productTypeData.id;

                        admin.req('enterprise/product/admin/productAttributeCategory/add', d.field, function (res) {
                            layer.closeAll('loading');
                            if (res.code == 200) {
                                layer.msg(res.msg, {icon: 1});
                                layer.close(openCategoryIndex);
                            } else {
                                layer.msg(res.msg, {icon: 2});
                            }
                        }, 'POST');
                        return false;
                    });
                }
            })
        }
    });
</script>